#include <my_header.h>

typedef struct share_value_s{
    int flag;
    pthread_mutex_t mutex;
    pthread_cond_t cond_a;
    pthread_cond_t cond_b;
}share_value_t;

void * threadFunc(void * arg);
void funA();
void funB();
void funC();
/* usage */
int main(int argc, char *argv[])
{
    ARGS_CHECK(argc,1);

    share_value_t share_value;
    share_value.flag = 0;
    pthread_mutex_init(&share_value.mutex,NULL);
    pthread_cond_init(&share_value.cond_a,NULL);
    pthread_cond_init(&share_value.cond_b,NULL);

    pthread_t tid;
    int ret_create = pthread_create(&tid,NULL,threadFunc,&share_value);
    THREAD_ERROR_CHECK(ret_create,"pthread_create");

    funA();

    pthread_mutex_lock(&share_value.mutex);
    share_value.flag = 1;
    pthread_cond_signal(&share_value.cond_a);

    while(share_value.flag != 2)
    {
        pthread_cond_wait(&share_value.cond_b,&share_value.mutex);
    }
    pthread_mutex_unlock(&share_value.mutex);

    funC();
    pthread_join(tid,NULL);

    return 0;
}

void * threadFunc(void * arg)
{
    share_value_t * pshare_value = (share_value_t *)arg;

    pthread_mutex_lock(&pshare_value->mutex);
    while(pshare_value->flag ==0)
    {
        pthread_cond_wait(&pshare_value->cond_a,&pshare_value->mutex);
    }
    funB();
    pshare_value->flag = 2;
    pthread_cond_signal(&pshare_value->cond_b);
    pthread_mutex_unlock(&pshare_value->mutex);

    pthread_exit(NULL);
}

void funA()
{
    printf("I am funA.\n");
}

void funB()
{
    printf("I am funB.\n");
}

void funC()
{
    printf("I am funC.\n");
}
